﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using UserSessionService.WebApi.DataLayer;

namespace UserSessionService.WebApi.Controllers
{
    public class ViewedItemsController : ApiController
    {
        private IUserSessionRepository repo = null;

        public ViewedItemsController(IUserSessionRepository sessionRepository)
        {   
            // IoC created session repository and passed it as a parameter
            repo = sessionRepository;  
        }

        // DELETE api/vieweditems
        // To test: use Fiddler. 
        // send delete to http://localhost:3785/api/vieweditems/
        //
        [HttpDelete]
        [ActionName("delete")]
        public HttpResponseMessage DeleteViewedItems()
        {
            repo.DeleteViewedItems();
            var responseMsg = Request.CreateResponse(HttpStatusCode.OK);
            return responseMsg;
        }

        // POST api/vieweditems
        // To test: use Fiddler. 
        // send post to http://localhost:3785/api/vieweditems using request body: {"userId" : "user1@hotmail.com", "prodId" :  "154a0fdb8c0e7c691201"}
        //
        [HttpPost]
        [ActionName("default")]
        public HttpResponseMessage AddViewedItem([FromBody]JObject json)
        {
            string userId = (string)json.GetValue("userId");
            string prodId = (string)json.GetValue("prodId");

            repo.AddViewedItem(userId, prodId);
            var responseMsg = Request.CreateResponse(HttpStatusCode.Created);
            return responseMsg;
        }

        // GET api/vieweditems/{userId}?count={n}
        // Eg. api/vieweditems/dXNlcjFAaG90bWFpbC5jb20=?count=5
        //
        // To test: use browser. 
        //         http://localhost:3785/api/vieweditems/dXNlcjFAaG90bWFpbC5jb20=?count=5 
        //         http://localhost:3785/api/vieweditems/dXNlcjFAaG90bWFpbC5jb20= //defaults count to 5
        //
        [HttpGet]
        [ActionName("default")]
        public HttpResponseMessage GetViewedItems(string encodedUserId, [FromUri] int count = 5)
        {
            if (!(count > 0) && (count <= 10))
                return Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest,
                    string.Format("Count request {0} is invalid. Must be greater than 0 and less than or equal to 10.", count)
                );

            string userId;
            //Trying to decode the userId will result in an error if the encodedUserId is not a properly encoded userId
            //If this happens, return a 401, Unauthorised
            try { userId = Encoding.Default.GetString(Convert.FromBase64String(encodedUserId)); }
            catch (Exception)
            {
                return Request.CreateErrorResponse(
                    HttpStatusCode.Unauthorized,
                    string.Format("UserId {0} is invalid.", encodedUserId)
                );
            }

            var items = repo.GetViewedItems(userId, count);

            if (items != null && items.Count() > 0)
                return Request.CreateResponse<List<string>>(HttpStatusCode.OK, items);
            
            else
                return Request.CreateErrorResponse(
                    HttpStatusCode.NotFound, string.Format("No viewed items for user: {0}.", userId)        // dk - changed return message
                );
        }
    }
}
